package com.jmp.security.response;

import com.jmp.base.dto.MessageSavePushRequest;
import com.jmp.feign.MessageFeign;
import com.jmp.security.base.*;
import lombok.extern.slf4j.Slf4j;
import one.stand.entity.TokenEntity;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

@Slf4j
public class SuccessResponseHandlerImpl implements ResponseHandler {
    private MessageFeign messageFeign;

    public SuccessResponseHandlerImpl(MessageFeign messageFeign) {
        this.messageFeign = messageFeign;
    }

    @Override
    public ResponseDetail handler(RequestDetail requestDetail, ClientDetail detail, UserDetail userDetail, TokenEntity tokenEntity, Exception e) {
        log.info("success handler");

        savePush(userDetail.getUserModel().getUserId(), requestDetail.getPushCid(), Objects.nonNull(detail) && Objects.nonNull(detail.getSecurityClient()) ? detail.getSecurityClient().getPushId() : null);

        return ResponseDetail.builder()
                .isSuccess(true)
                .token(tokenEntity.getToken())
                .userDetail(userDetail)
                .build();
    }

    private void savePush(Integer userId, String pushCid, String pushAppId) {
        if (StringUtils.isBlank(pushCid)) return;
        if (Objects.isNull(pushAppId)) return;

        if (StringUtils.isNoneBlank(pushAppId)) {
            MessageSavePushRequest messageSavePushRequest = MessageSavePushRequest.builder()
                    .userId(userId)
                    .companyKey(pushAppId)
                    .pushCid(pushCid)
                    .build();
            messageFeign.savePush(messageSavePushRequest);
        }
    }
}
